package com.example.maggie.meizinote.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.widget.Toast;

import com.example.maggie.meizinote.app.bean.MyUser;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.example.maggie.meizinote.mvp.contract.RegisterContract;

import static android.app.Activity.RESULT_OK;


@ActivityScope
public class RegisterPresenter extends BasePresenter<RegisterContract.Model, RegisterContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public RegisterPresenter(RegisterContract.Model model, RegisterContract.View rootView) {
        super(model, rootView);
    }

    public void onRechangePassword(String email) {
        BmobUser.resetPasswordByEmail(email, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    mRootView.showDialog("重置密码请求成功，请到" + email + "邮箱进行密码重置操作！", true);
                } else mRootView.showDialog("操作失败：" + e.getMessage(), false);
            }
        });
    }

    public void onRegister(String email, String pwd, String repwd) {
        if (!pwd.equals(repwd)) {
            mRootView.showMessage("两次密码不一致，重新输入!");
            return;
        }
        BmobUser bu = new BmobUser();
        bu.setEmail(email);
        bu.setUsername(email);
        bu.setPassword(pwd);
        bu.signUp(new SaveListener<MyUser>() {
            @Override
            public void done(MyUser s, BmobException e) {
                if (e == null) {
                    mRootView.result(email, pwd);
                } else {
                    if (e.getErrorCode()==301) mRootView.showMessage("邮箱格式不正确");
                    if (e.getErrorCode()==202) mRootView.showMessage("用户名已经存在");
                    if (e.getErrorCode()==304) mRootView.showMessage("用户名或密码为空");
                    else{
                        mRootView.showMessage(e + "");
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

}
